<?php

namespace app\controller;

use app\model\Shop;
use app\Request;
use GuzzleHttp\Client;
use think\facade\Config;

class Callback
{
    /**
     * 微盟回调逻辑
     */
    public function weimeng(Request $request) {
        $code = $request->get('code');
        $state = $request->get('state');
        if (empty($code) || empty($state)) {
            return $this->view('必传参数不能为空', false);
        }
        $shop = Shop::find($state);
        if (empty($shop)) {
            return $this->view('店铺不存在', false);
        }
        $client = new Client();
        $url = Config::get('tap.platform.1.token_url');
        $redirect_uri = url('/weimeng', [], true, true)->build();;
        $query = [
            'code' => $code,
            'grant_type' => 'authorization_code',
            'client_id' => $shop->params->client_id,
            'client_secret' => $shop->params->client_secret,
            'redirect_uri' => $redirect_uri
        ];
        $rep = $client->post($url, ['query' => $query, 'verify' => false, 'http_errors' => false])->getBody()->getContents();
        $token = json_decode($rep, true);
        if (isset($token['error_description'])) {
            return $this->view($token['error_description'], false);
        }
        $shop->params->access_token = $token['access_token'] ?? '';
        $shop->params->refresh_token = $token['refresh_token'] ?? '';
        $shop->save();
        return $this->view('授权成功,请手动关闭窗口');
    }

    private function view($msg = '', $is_success = true): string
    {
        $notice = $is_success ? '授权成功' : '授权失败';
        return <<< HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>$notice</title>
</head>
<body>
<div id="backstage-bodyArea">
        <div class="picture-resize-wrap "
             style="position: relative; width: 100%; text-align: center; ">
            <span style="display: inline-block;vertical-align: middle; position: relative; max-width: 100%; ">
            <img src="//5ornrwxhlkjnj.leadongcdn.cn/cloud/knBnqKSRkijlinr/fasongchenggong.jpg">
            </span>
        </div>
        <div style="text-align: center;margin: 20px">$notice</div>
    <div style="text-align: center;margin-top: 40px">
        <div> $msg </div>
    </div>
</div>
</body>
</html>
HTML;
    }
}
